import os
from win32com.client import Dispatch, constants, gencache, DispatchEx
import win32com.client


class PDFConverter:
    def __init__(self, pathname, output, export='.'):
        self._handle_postfix = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx']
        self._filename_list = list()
        self._export_folder = os.path.join(os.path.abspath('.'), output)
        if not os.path.exists(self._export_folder):
                os.mkdir(self._export_folder)
        self._enumerate_filename(pathname)
    
    def _enumerate_filename(self, pathname):
        '''
        读取所有文件名
        '''
        full_pathname = os.path.abspath(pathname)
        if os.path.isfile(full_pathname):
            if self._is_legal_postfix(full_pathname):
                self._filename_list.append(full_pathname)
            else:
                raise TypeError('文件 {} 后缀名不合法！仅支持如下文件类型：{}。'.format(pathname, '、'.join(self._handle_postfix)))
        elif os.path.isdir(full_pathname):
            for relpath, _, files in os.walk(full_pathname):
                for name in files:
                    filename = os.path.join(full_pathname, relpath, name)
                    if self._is_legal_postfix(filename):
                        self._filename_list.append(os.path.join(filename))
        else:
            raise TypeError('文件/文件夹 {} 不存在或不合法！'.format(pathname))

    def _is_legal_postfix(self, filename):
        return filename.split('.')[-1].lower() in self._handle_postfix and not os.path.basename(filename).startswith('~')
    
    def run_conver(self):
        '''
        进行批量处理，根据后缀名调用函数执行转换
        '''
        print('需要转换的文件数：', len(self._filename_list))
        for filename in self._filename_list:
            postfix = filename.split('.')[-1].lower()
            funcCall = getattr(self, postfix)
            print('原文件：', filename)
            funcCall(filename)
        print('转换完成！')

        
    def ConvertDocToPdf(self, filename):
        '''
        :param src: 待转换word文档 
        :param dst: 转换完成后的pdf文档
        :return: 
        '''
        if not os.path.exists(filename):
            print(src + "not exist, couldn't convert")
            return False
       
        name = os.path.basename(filename).split('.')[0] + '.pdf'
        exportfile = os.path.join(self._export_folder, name)
        if os.path.exists(exportfile):
            os.remove(exportfile)
        o = win32com.client.Dispatch("Kwps.Application")
        o.Visible = False
        doc = o.Documents.Open(filename);
        doc.ExportAsFixedFormat(exportfile, 17)
        o.Quit();
      

    
    def doc(self, filename):
        '''
        doc 和 docx 文件转换
        '''
        if not os.path.exists(filename):
            print(filename + "not exist, couldn't convert")
            return False
        os.system('taskkill /im wps.exe')

        name = os.path.basename(filename).split('.')[0] + '.pdf'
        exportfile = os.path.join(self._export_folder, name)
        if os.path.exists(exportfile):
            os.remove(exportfile)
        o = win32com.client.Dispatch("Kwps.Application")
        o.Visible = False
        doc = o.Documents.Open(filename);
        doc.ExportAsFixedFormat(exportfile, 17)
        o.Quit();
    
    def docx(self, filename):
        self.doc(filename)
    
    def xls(self, filename):
        '''
        xls 和 xlsx 文件转换
        '''
        if not os.path.exists(filename):
            print(filename + "不存在，无法继续！")
            return False
        os.system('taskkill /im wps.exe')
        name = os.path.basename(filename).split('.')[0] + '.pdf'
        exportfile = os.path.join(self._export_folder, name)
        if os.path.exists(exportfile):
            os.remove(exportfile)
        xlApp = win32com.client.Dispatch("Ket.Application")
        excel = xlApp.Workbooks.Open(filename)
        excel.ExportAsFixedFormat(0, exportfile)
        excel.Close()
        xlApp.Quit()
    
    def xlsx(self, filename):
        self.xls(filename)
    
    def ppt(self, filename):
        '''
        ppt 和 pptx 文件转换
        '''
        if not os.path.exists(filename):
            print(filename + "不存在，无法继续！")
            return False
        os.system('taskkill /im wps.exe')
        name = os.path.basename(filename).split('.')[0] + '.pdf'
        exportfile = os.path.join(self._export_folder, name)
        if os.path.exists(exportfile):
            os.remove(exportfile)
        wpp = win32com.client.Dispatch("Kwpp.Application")
        ppt = wpp.Presentations.Open(filename)
        ppt.SaveAs(exportfile, 32)
        ppt.Close()
        wpp.Quit()
    
    def pptx(self, filename):
        self.ppt(filename)



if __name__ == "__main__":
    input_folder = 'input'
    output_folder = "output"
    pathname = os.path.join(os.path.abspath('.'), input_folder)
    pdfConverter = PDFConverter(pathname,output_folder)
    pdfConverter.run_conver()
